<?php
	
	require_once(dirname(__FILE__) . "/../core/safeParam.php");
	
	if (isset($_POST['gateway_name'])) {
		$input['gateway_settings'] = serialize($_POST['gateway_settings']);
  		$gateways                  = $database->select("SELECT * from gateway where name = '" . $_POST['gateway_name'] . "' and rid = " . ARID . "");
  		$vars['display']           = $_POST['display'];
  		$vars['name']              = $_POST['gateway_name'];
  		$vars['options']           = $input['gateway_settings'];
  		$vars['enabled']           = $_POST['enabled'];
  		$vars['rid']               = ARID;
  		
  		if ($gateways == FALSE) {
  			$database->insert_array("gateway", $vars);
  		} else {
  			$database->update_array("gateway", $vars, "name = '" . $_POST['gateway_name'] . "'");
  		}
  		
  		echo '
  		<script type="text/javascript">
	      <!--
      		window.location = "index.php?edit=gateway"
      	//-->
      </script>';
	}
?>

<?php
	$query   = $database->query("SELECT * FROM config where id = " . ARID . "  ");
	$results = mysql_fetch_array($query);
	
	// define the path as relative
	$gateway = $results['gateway'];
	$path    = "../modules/gateway/";
	$dir_handle = @opendir($path) or die("Unable to open $path");

	function gateway_check_status($gateway){
  		global $database;
  		
  		$r = $database->select("SELECT * FROM gateway where name = '$gateway' and rid =  " . ARID . "  ");
  		
  		if ($r[0]['enabled'] == 1) {
    		return '<span style="color:green">Activado</span>';
  		} else {
    		return '<span style="color:red">Desactivado</span>';
  		}
	}
	
	echo '
	<div class="tituloOpcionesAdmin">
		<img src="images/icons/credit.png"/>
		Modo de cobro		
	</div>
	
	<div class="descripcionOpcionesAdmin">
		Debe configurar el modo de cobranza de sus servicios. Actualmente sólo damos soporte al modo "cash". 
		Estamos trabajando para que proximamente se puedan realizar promociones, descuentos, cupones, etc.
	</div>
	
	<table class="table">
		<tr>
			<th>Nombre</th>
      	<th>Estado</th>
      	<th>Acción</th>
		</tr>';
	
	while ($file = readdir($dir_handle)) {
		if (($file == '.') or ($file == '..') or ($file == '.htaccess') or (is_dir($file))) {} 
  		else {
    		if (is_dir('../modules/gateway/' . $file . '')) {
    			echo '
    			<tr>
    				<td>
    					'. $file .'
    				</td>    			
    				
    				<td>
    					'. gateway_check_status($file) .'
    				</td>
    				
    				<td>
    					<a href="index.php?edit=gateway&gateway=' . $file . '">
    						Configurar
    					</a>
    				</td>
    			</tr>';
    		} 
  		}
	}
	
	echo '</table>';
	closedir($dir_handle);

	if(isset($_GET['gateway'])){
		if ($_GET['gateway'] != "") {
?>

<br />

<div class="tituloOpcionesAdmin">
	Modo de cobro: <i><?php echo $_GET['gateway'];?></i> 
</div>

<div id="gateway">
	<?php
		include '../modules/gateway/' . $_GET['gateway'] . '/admin.php'; 
	?> 
</div>

<?php
		}
	}
?>